# Base authenticated class.  Inherit from this class, don't put any app-specific code in here.
# That way we can update this model if auth_generators update.

require 'digest/sha1'
module AuthenticatedBase
  def self.included(base)
    
    base.set_table_name base.name.tableize

    base.validates_presence_of     <% if !options[:use_email] %>:login,<% end %> :email
    base.validates_presence_of     :password,                   :if => :password_required?
    base.validates_presence_of     :password_confirmation,      :if => :password_required?
    base.validates_length_of       :password, :within => 4..40, :if => :password_required?
    base.validates_confirmation_of :password,                   :if => :password_required?
    <% if !options[:use_email] %>
    base.validates_length_of       :login,    :within => 3..40
    base.validates_uniqueness_of   :login, :email, :case_sensitive => false
    <% end %>
    base.validates_length_of       :email,    :within => 3..100
    base.before_save :encrypt_password
    <% if options[:include_activation] %>base.before_create :make_activation_code <% end %>

    base.cattr_accessor :current_user
    base.attr_accessible <% if !options[:use_email] %>:login,<% end %> :email, :password, :password_confirmation
    
    base.extend ClassMethods
  end

  attr_accessor :password

  class ActivationCodeNotFound < StandardError; end
  class AlreadyActivated < StandardError
    attr_reader :<%= file_name %>, :message;
    def initialize(<%= file_name %>, message=nil)
      @message, @<%= file_name %> = message, <%= file_name %>
    end
  end

  module ClassMethods
    
    <% if options[:include_activation] %>
    def find_and_activate!(activation_code)
      raise ArgumentError if activation_code.nil?
      <%= file_name %> = find_by_activation_code(activation_code)
      raise ActivationCodeNotFound if !user
      raise AlreadyActivated.new(<%= file_name %>) if <%= file_name %>.activated?
      <%= file_name %>.send(:activate!)
      <%= file_name %>
    end
    <% end %>
    
    ## Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
    <% if options[:use_email] %>
    def authenticate(email, password)
      u = <% if options[:include_activation] %>find :first, :conditions => ['email = ? and activated_at IS NOT NULL', email]<% else %>find_by_email(email)<% end %> # need to get the salt
	    u && u.authenticated?(password) ? u : nil
    end
    <% else %>
    def authenticate(login, password)
      u = <% if options[:include_activation] %>find :first, :conditions => ['login = ? and activated_at IS NOT NULL', login]<% else %>find_by_login(login)<% end %> # need to get the salt
      u && u.authenticated?(password) ? u : nil
    end
    <% end %>
  
    # Encrypts some data with the salt.
    def encrypt(password, salt)
      Digest::SHA1.hexdigest("--#{salt}--#{password}--")
    end
  
  end
  
  <% if options[:include_activation] %>
    # Activates the user in the database.

    def activated?
      # the existence of an activation code means they have not activated yet
      activation_code.nil?
    end

    # Returns true if the user has just been activated.
    def recently_activated?
      @activated
    end
  <% end %>
  # Encrypts the password with the user salt
  def encrypt(password)
    self.class.encrypt(password, salt)
  end

  def authenticated?(password)
    crypted_password == encrypt(password)
  end
  
  def remember_token?
    remember_token_expires_at && Time.now.utc < remember_token_expires_at 
  end
  
  # These create and unset the fields required for remembering users between browser closes
  def remember_me
    remember_me_for 2.weeks
  end
  
  def remember_me_for(time)
    remember_me_until time.from_now.utc
  end
  
  # Useful place to put the login methods
  def remember_me_until(time)
    self.remember_token_expires_at = time
    self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
    save(false)
  end
  
  def forget_me
    self.remember_token_expires_at = nil
    self.remember_token            = nil
    save(false)
  end
  
  <% if options[:password_management] %>
  def forgot_password
   @forgotten_password = true
   self.make_password_reset_code
  end

  def reset_password
   # First update the password_reset_code before setting the 
   # reset_password flag to avoid duplicate email notifications.
   update_attributes(:password_reset_code => nil)
   @reset_password = true
  end

  def recently_reset_password?
   @reset_password
  end

  def recently_forgot_password?
   @forgotten_password
  end
  
  def make_password_reset_code
    self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
  end
  <% end %>
  
  def encrypt_password
    return if password.blank?
    <% if options[:use_email] %>
    self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{email}--") if new_record?
    <% else %>
    self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
    <% end %>
    self.crypted_password = encrypt(password)
  end
    
  def password_required?
    (crypted_password.blank? || !password.blank?)
  end
  
  <% if options[:include_activation] %>
  def activate!
    @activated = true
    self.update_attribute(:activated_at, Time.now.utc)
  end
  
  def make_activation_code
    self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
  end
  <% end %>
end
